﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
using Framework.Common.Attributes;
using Framework.Serializer;
namespace Framework.Sample
{
    [OrderedDesc("5)    Emit hello world")]
    class Test5 : ITest
    {
        public void Run()
        {
            Console.WriteLine(@"Emit hello world");
            var asmName = new AssemblyName("Test");

            var asmBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(

                asmName,

                AssemblyBuilderAccess.RunAndSave);

            var mdlBldr = asmBuilder.DefineDynamicModule("Main", "Main.exe");

            var typeBldr = mdlBldr.DefineType("Hello", TypeAttributes.Public);

            var methodBldr = typeBldr.DefineMethod(

                "SayHello",

                MethodAttributes.Public | MethodAttributes.Static,

                null,//return type               

                null//parameter type       

                );

            var il = methodBldr.GetILGenerator();//获取il生成器  

            il.Emit(OpCodes.Ldstr, "Hello, World");

            il.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }));

            il.Emit(OpCodes.Call, typeof(Console).GetMethod("ReadLine"));

            il.Emit(OpCodes.Pop);//读入的值会被推送至evaluation stack，而本方法是没有返回值的，因此，需要将栈上的值抛弃    

            il.Emit(OpCodes.Ret);

            var t = typeBldr.CreateType();

            asmBuilder.SetEntryPoint(t.GetMethod("SayHello"));

            asmBuilder.Save("Main.exe");
        }
    }
}
